import React from 'react'
import { StyleSheet, View, Text } from 'react-native'
import PropTypes from 'prop-types'
import moment from 'moment'
import Animated from 'react-native-reanimated'
import { TabView } from 'react-native-tab-view'
import { ScaleS, ScaleT, ONE_PIXEL, WIDTH } from 'src/utils/ScreenUtil'
import CustomButton from 'src/components/button/CustomButton'
import CustomFlatList from 'src/components/custom-flat-list/index'
import RefreshState from 'src/components/custom-flat-list/RefreshState'
import EmptyView from 'src/components/empty-view/index'
import { findUserResumeByChannelId } from 'src/utils/RequestAPI'
import { calcTimeHeader } from 'src/utils/TimeUtil'
import NavigationUtil from 'src/utils/NavigationUtil'
import { schoolPostStates, getGenderChinese } from 'src/utils/ConfigUtil'
import CustomImage from 'src/components/image/CustomImage'

export default class ArchiveList extends React.Component {
  static propTypes = {
    channelId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    jumpThrowResume: PropTypes.func
  }

  limit = 10

  constructor(props) {
    super(props)
    const activeIndex = props.routerName === '已录用' ? 2 : 0
    this.state = {
      activeIndex,
      routes: [
        {
          key: 'state0',
          title: '待处理',
          type: '0',
          index: 0
        },
        {
          key: 'state1',
          title: '面试中',
          type: '5',
          index: 1
        },
        {
          key: 'state2',
          title: '已录用',
          type: '2',
          index: 2
        },
        {
          key: 'state3',
          title: '不合适',
          type: '1',
          index: 3
        }
      ],
      tabDatas: [
        {
          page: 1,
          data: null
        },
        {
          page: 1,
          data: null
        },
        {
          page: 1,
          data: null
        },
        {
          page: 1,
          data: null
        }
      ]
    }
  }

  render() {
    const { activeIndex, routes } = this.state
    return (
      <TabView
        navigationState={{
          index: activeIndex,
          routes
        }}
        renderScene={this.renderScene}
        renderTabBar={this.renderTabBar}
        onIndexChange={this.setTabIndex}
        initialLayout={{ width: WIDTH }}
        timingConfig={{ duration: 0.01 }}
      />
    )
  }

  componentDidMount() {
    this._onHeaderRefresh(this.state.activeIndex)
  }

  setTabIndex = activeIndex => {
    this.setState({ activeIndex })
    if (!this.state.tabDatas[activeIndex].data) {
      this._onHeaderRefresh(activeIndex)
    }
  }

  renderTabBar = props => {
    const { index, routes } = props.navigationState
    return (
      <View style={styles.tabBar}>
        {routes.map((route, i) => {
          return (
            <CustomButton
              key={i}
              params={i}
              style={[styles.tabItem, i === index && styles.tabItemActive]}
              onPress={this.setTabIndex}
            >
              <Animated.Text
                style={[styles.tabText, i === index && styles.activeTabText]}
              >
                {route.title}
              </Animated.Text>
            </CustomButton>
          )
        })}
      </View>
    )
  }

  renderScene = ({ route }) => {
    const { index } = route
    const { tabDatas } = this.state
    return (
      <View style={styles.container}>
        <CustomFlatList
          index={index}
          ref={this._setFlatListRef}
          style={styles.flatList}
          renderItem={this._renderItem}
          data={tabDatas[index].data || []}
          keyExtractor={this._keyExtractor}
          onHeaderRefresh={this._onHeaderRefresh}
          onFooterRefresh={this._onFooterRefresh}
          ListEmptyComponent={this._listEmptyComponent()}
          showsVerticalScrollIndicator={false}
        />
      </View>
    )
  }

  flatLists = []

  _setFlatListRef = ref => {
    if (ref && ref.props) {
      const { index } = ref.props
      this.flatLists[index] = ref
    }
  }

  jumpThrowResume = ({ item }) => {
    const callback = (state = this.state.activeIndex) => {
      // 投递情况 0,未处理。1，不合适，2,直接录用 3初试 4，二面，5三面,6，四面"
      /* eslint-disable */
      const dic = {
        '0': 0,
        '3': 1,
        '4': 1,
        '5': 1,
        '6': 1,
        '2': 2,
        '1': 3
      }
      const nextIndex = dic[state.toString()]
      const { activeIndex } = this.state
      if (activeIndex !== nextIndex) {
        const { tabDatas } = this.state
        const { page, data } = tabDatas[activeIndex]
        const id = `${item.postId}${item.userId}`
        tabDatas[activeIndex] = {
          page,
          data: data.filter(e => `${e.postId}${e.userId}` !== id)
        }
        this.setState({
          tabDatas: [...tabDatas]
        }, () => {
          this._onHeaderRefresh(nextIndex)
        })
      }
    }
    NavigationUtil.navigate('ThrowResume', {
      postId: item.postId,
      channelId: item.channelId,
      userId: item.userId,
      callback
    })
  }

  _renderItem = data => {
    const {
      item: {
        userName,
        userAvator,
        gender,
        age,
        education,
        time,
        postName,
        jobPlace,
        schoolName,
        majorname
      }
    } = data
    return (
      <CustomButton onPress={this.jumpThrowResume} params={data} style={styles.itemContainer}>
        <View style={styles.topView}>
          <CustomImage style={styles.userAvator} source={{ uri: userAvator }} />
          <View style={styles.topCenter}>
            <Text style={styles.userName}>{userName}</Text>
            <Text style={styles.gender}>{getGenderChinese(gender)}{age ? `·${age}岁` : ''}{education ? `·${education}` : ''}</Text>
          </View>
          <Text style={styles.time}>{calcTimeHeader(moment(time).valueOf())}</Text>
        </View>
        <Text style={styles.perfer}>意向职位：<Text style={styles.postName}>{postName}{jobPlace ? `·${jobPlace}` : ''}</Text></Text>
        <Text style={styles.schoolName}>{schoolName}{majorname ? `·${majorname}` : ''}</Text>
      </CustomButton>
    )
  }

  _keyExtractor = item => {
    return item.userId.toString() + item.postId
  }

  _onHeaderRefresh = (activeIndex = this.state.activeIndex) => {
    console.log('_onHeaderRefresh====>', activeIndex)
    const { channelId } = this.props
    const { type } = this.state.routes[activeIndex]
    return findUserResumeByChannelId({
      params: { page: 1, limit: this.limit, channelId, type }
    })
      .then(({ data }) => {
        const { tabDatas } = this.state
        tabDatas[activeIndex] = {
          page: 1,
          data
        }
        this.setState({
          tabDatas: [...tabDatas]
        })
        this._setEndRefreshingState(data, activeIndex)
      })
      .catch(() => {
        this._setEndRefreshingState(null, activeIndex)
      })
  }

  _onFooterRefresh = (activeIndex = this.state.activeIndex) => {
    console.log('_onFooterRefresh====>', activeIndex)
    const { channelId } = this.props
    const { type } = this.state.routes[activeIndex]
    findUserResumeByChannelId({
      params: {
        page: this.state.tabDatas[activeIndex].page + 1,
        limit: this.limit,
        channelId,
        type
      }
    })
      .then(({ data }) => {
        const { tabDatas } = this.state
        tabDatas[activeIndex] = {
          page: tabDatas[activeIndex].page + 1,
          data: [...tabDatas[activeIndex].data, ...data]
        }
        this.setState({
          tabDatas: [...tabDatas]
        })
        this._setEndRefreshingState(data, activeIndex)
      })
      .catch(() => {
        this._setEndRefreshingState(null, activeIndex)
      })
  }

  _setEndRefreshingState = (data, activeIndex) => {
    if (data) {
      if (data.length > 9) {
        this._setEndRefreshState(RefreshState.CanLoadMore, activeIndex)
      } else {
        this._setEndRefreshState(RefreshState.NoMoreData, activeIndex)
      }
    } else {
      this._setEndRefreshState(RefreshState.Failure, activeIndex)
    }
  }

  _setEndRefreshState = (state, activeIndex) => {
    this.flatLists[activeIndex] &&
      this.flatLists[activeIndex].endRefreshing &&
      this.flatLists[activeIndex].endRefreshing(state)
  }

  _listEmptyComponent = () => {
    return (
      <EmptyView
        emptyImg={require('src/imgC/home/post_no_data.png')}
        style={styles.emptyView}
        firstTip={'...'}
      />
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    position: 'relative',
    backgroundColor: '#F9FAFA'
  },
  tabBar: {
    height: ScaleS(41),
    paddingHorizontal: ScaleS(20),
    paddingBottom: ScaleS(11),
    backgroundColor: '#FFFFFF',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  tabItem: {
    justifyContent: 'center',
    alignItems: 'center',
    width: ScaleS(72),
    height: '100%'
  },
  tabItemActive: {
    backgroundColor: '#F2F3F5',
    borderRadius: ScaleS(16)
  },
  tabText: {
    fontSize: ScaleT(13),
    fontWeight: '400',
    color: '#CCCCCC'
  },
  activeTabText: {
    color: '#666666'
  },
  flatList: {
    flex: 1
  },
  itemContainer: {
    paddingLeft: ScaleS(27),
    paddingTop: ScaleS(30),
    paddingRight: ScaleS(20),
    paddingBottom: ScaleS(13),
    paddingVertical: ScaleS(16),
    borderColor: 'rgba(151, 151, 151, 0.25)',
    borderBottomWidth: ONE_PIXEL
  },
  topView: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  userAvator: {
    width: ScaleS(40),
    height: ScaleS(40),
    borderRadius: ScaleS(20),
    resizeMode: 'cover'
  },
  topCenter: {
    flex: 1,
    marginHorizontal: ScaleS(10),
    justifyContent: 'center'
  },
  userName: {
    fontSize: ScaleT(14),
    lineHeight: ScaleS(20),
    fontWeight: '500',
    color: '#3C3C3C'
  },
  gender: {
    fontSize: ScaleT(10),
    lineHeight: ScaleS(19),
    fontWeight: '400',
    color: '#CCCCCC'
  },
  time: {
    fontSize: ScaleT(13),
    fontWeight: '400',
    color: '#CCCCCC'
  },
  perfer: {
    marginTop: ScaleS(15),
    marginLeft: ScaleS(50),
    lineHeight: ScaleS(23),
    fontSize: ScaleT(16),
    fontWeight: '300',
    color: '#3C3C3C'
  },
  postName: {
    fontWeight: '400'
  },
  schoolName: {
    marginTop: ScaleS(5),
    marginLeft: ScaleS(50),
    lineHeight: ScaleS(24),
    fontSize: ScaleT(14),
    fontWeight: '400',
    color: '#999999'
  }
})
